import router from '@/router/index.js'
import settings from '@/settings.js'
import {ElLoading, ElMessage} from 'element-plus'

// export const is_dev = () => {
//   return import.meta.env.VITE_ENV === 'development'
// }

/**
 *
 * @param {string} str
 * @returns {any|boolean}
 */
export function isObjectJson (str) {
  try {
    const result = JSON.parse(str)
    return Object.prototype.toString.call(result).slice(8, -1) === 'Object';
  } catch (e) {
    return false
  }
}

export function titleSetting() {
  router.beforeEach((to, from, next) => {
    let toTitle = ''
    if (to.meta) {
      const {title} = to.meta
      toTitle = title
    }
    window.document.title = (toTitle ? toTitle + '-' : '') + settings.title
    next()
  })
}
//
// export function objectToQuery(object) {
//   let query = ''
//   Object.keys(object).forEach((key) => {
//     query += `&${key}=${object[key]}`
//   })
//   return query.substring(1)
// }

/**
 * @param length
 * @returns {string}
 */
export function randomString(length = 5) {
  const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
  const len = str.length
  const result = []
  for (let i = 0; i < length; i++) {
    let random = Math.floor(Math.random() * len)
    result.push(str.substring(random, random + 1))
  }
  return result.join('')
}

export const beforeUpload = (file, max_size = 3) => {
  let type_arr = ['image/jpeg', 'image/png']
  let type = file.type
  if (!type_arr.includes(type)) {
    ElMessage.error('图片格式不正确,只支持jpg和png类型图片')
    return false
  }
  if (file.size > 1024 * 1024 * max_size) {
    ElMessage.error(`图片大小请不要超过${max_size}M`)
    return false
  }
  ElLoading.service({fullscreen: true, text: '图片上传中，请稍后..'})
}

export const handleExceed = (files, limit) => {
  if (files.length > limit) {
    ElMessage.warning(`最多可上传${limit}张图片`)
  }
}

export const uploadError = () => {
  ElMessage.error('上传失败，请重新上传')
  ElLoading.service({fullscreen: true}).close()
}

export function getSelection() {
  let selection
  if (window.getSelection) {
    selection = window.getSelection()
  } else {
    selection = document.selection.createRange()
  }
  return selection
}

export function getDocumentStr(elementId) {
  const element = document.getElementById(elementId)
  element.querySelectorAll('.select-none').forEach(el => {
    el.style.display = 'none'
  })
  const range = document.createRange()
  range.selectNodeContents(element)
  const selection = getSelection()
  selection.removeAllRanges()
  selection.addRange(range)
  const str = selection.toString().trim()
  selection.removeAllRanges()
  element.querySelectorAll('.select-none').forEach(el => {
    el.style.display = 'block'
  })
  return str
}

export function copyDocumentStr(elementId) {
  copyString(getDocumentStr(elementId))
}

export function copyString(str) {
  const el = document.createElement('textarea')
  el.value = decodeURIComponent(str)
  el.setAttribute('readonly', '')
  el.style.position = 'absolute'
  el.style.left = '-9999px'
  document.body.appendChild(el)
  const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false
  el.select()
  document.execCommand('copy')
  document.body.removeChild(el)
  if (selected) {
    document.getSelection().removeAllRanges()
    document.getSelection().addRange(selected)
  }
  ElMessage.success({message: '已复制到剪切板'})
}

export function highlightBlock(str, lang, code) {
  return `
<pre class="code-block-wrapper">
  <div class="code-block-header">
    <span class="code-block-header__lang select-none" style="user-select: none">${lang}</span>
      <span class="code-block-header__copy select-none" onclick="copyString(\`` + encodeURIComponent(code) + `\`)"> 复制代码 </span>
  </div>
  <code class="hljs code-block-body ${lang}">${str}</code>
</pre>`
}

export function formatFileSize(size) {
  const s = [4, 3, 2, 1, 0]
  const b = ['TB', 'GB', 'MB', 'KB', 'B']
  for (let i = 0; i < s.length; i++) {
    let m = Math.pow(1024, s[i])
    if (size > m) {
      return parseFloat((size / m).toFixed(2)) + ' ' + b[i]
    }
  }
}

export const getHost = () => {
  let hostHref = window.document.location.href
  const isHttps = hostHref.startsWith("https://")
  const ht = isHttps ? 'https://' : 'http://'
  hostHref = hostHref.replace(ht, '')
  return ht + hostHref.split('/')[0]
}


export const getIconPath = (icon) => {
  const iconMap = {
    'Xmind': 'mindmap',
    'FlowChart': 'drawio',
    'Document': 'doc',
  }
  return iconMap[icon] ? iconMap[icon] : 'doc'
}

export const getNoteNameAndIcon = (r_items, r_selectNode) => {
  const fn = (items, selectNode) => {
    try {
      items.forEach((item) => {
        if (item.children && item.children.length) {
          let res = fn(item.children, selectNode)
          if (res) {
            throw new Error(res)
          }
        } else {
          if (item.type === 2 && item.id === selectNode) {
            throw new Error(JSON.stringify({label: item.label, icon: item.icon}))
          }
        }
      })
    } catch (e) {
      return e.message + ''
    }
    return null
  }
  const resultString = fn(r_items, r_selectNode)
  return resultString ? JSON.parse(resultString) : {label: '', icon: ''}
}

export function jsonToObject(str = '') {
  try {
    return JSON.parse(str)
  } catch (e) {
    return null
  }
}